package com.wsc.wsckeeper.managers;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;

import com.wsc.wsckeeper.R;
import com.wsc.wsckeeper.app.KApplication;
import com.wsc.wsckeeper.persistence.DatabaseHelper;
import com.wsc.wsckeeper.utils.FileUtils;

@SuppressLint({ "SimpleDateFormat", "SdCardPath" })
public class FileServiceManager extends BaseManager {
	public static final String FILE_TYPE = ".db";

	public static FileServiceManager instance;

	public static FileServiceManager getInstance() {
		if (instance == null) {
			instance = new FileServiceManager();
		}
		return instance;
	}

	private File getCurrentDatabaseFile() {
		return new File("/data/data/" + KApplication.getContext().getPackageName() + "/databases/", DatabaseHelper.DATABASE_NAME);
	}

	private File getBackupDatabaseFile(String name) {
		return new File(PreferenceManager.getInstance().getLocation(), name);
	}

	public void restoreDatabase(String name) throws IOException {
		File from = getBackupDatabaseFile(name);
		File to = getCurrentDatabaseFile();
		FileUtils.copyFile(from, to);
	}

	public void backupDatabase(String name) throws IOException {
		String pref = new SimpleDateFormat(ResourceManager.getStringValue(R.string.format_export)).format(new Date());

		File to = getBackupDatabaseFile(name + pref + FILE_TYPE);
		File from = getCurrentDatabaseFile();

		FileUtils.copyFile(from, to);
	}

	@Override
	public void onCreationComplete() {
		onRefresh();
	}

	@Override
	public void onRefresh() {
		FileUtils.mkDirStructure(PreferenceManager.getInstance().getLocation());
	}

	@Override
	public void onDestroy() {

	}
}
